<template>
  <!-- 统一使用view作为根元素 -->
  <view id="app" class="app-container">
    <!-- 原生导航栏 - 仅非H5平台显示 -->
    <!-- #ifndef H5 -->
    <uni-nav-bar
      v-if="showNavBar"
      :title="navTitle"
      :left-icon="navBackIcon"
      :right-text="navRightText"
      @clickLeft="handleBack"
      @clickRight="handleRightAction"
    />
    <!-- #endif -->

    <!-- 页面内容 -->
    <router-view />
  </view>
</template>

<script lang="ts">
import Vue from 'vue'
import { onErrorCaptured } from '@vue/composition-api'

export default Vue.extend({
  name: 'App',
  
  data() {
    return {
      showNavBar: true,
      navTitle: '我的应用',
      navBackIcon: 'back',
      navRightText: ''
    }
  },

  setup() {
    // 全局错误捕获
    onErrorCaptured((err, vm, info) => {
      console.error('组件错误:', err, info)
      uni.showToast({
        title: '功能异常',
        icon: 'none'
      })
      return false
    })
  },

  onLaunch() {
    console.log('App Launch')
    this.checkUpdate()
    this.initNavigation()
  },

  onShow() {
    console.log('App Show')
  },

  onHide() {
    console.log('App Hide')
  },

  methods: {
    handleBack() {
      if (getCurrentPages().length > 1) {
        uni.navigateBack()
      } else {
        uni.switchTab({ url: '/pages/home/index' })
      }
    },

    handleRightAction() {
      // 可根据业务需求自定义右侧按钮行为
      uni.showToast({
        title: '点击了右侧按钮',
        icon: 'none'
      })
    },

    checkUpdate() {
      // #ifdef APP-PLUS
      const updateManager = uni.getUpdateManager()
      updateManager.onCheckForUpdate(res => {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(() => {
            uni.showModal({
              title: '更新提示',
              content: '新版本已准备好，是否重启应用？',
              success: res => {
                if (res.confirm) {
                  updateManager.applyUpdate()
                }
              }
            })
          })
        }
      })
      // #endif
    },

    initNavigation() {
      // 可根据路由动态设置导航栏
      uni.onAppRoute((route) => {
        this.navTitle = route.meta?.title || '我的应用'
        this.showNavBar = route.meta?.showNav !== false
      })
    }
  }
})
</script>

<style lang="scss">
/* 全局样式 */
@import '@/static/styles/global.scss';
@import '@/static/styles/variables.scss';

.app-container {
  width: 100%;
  height: 100vh;
  font-family: $font-family-base;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: $text-color-primary;
  background-color: $background-color;
}

/* 全局过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>